package cn.wh.db.router.strategy;


import cn.hutool.core.util.StrUtil;
import cn.wh.db.router.DBRoutingConfig;
import cn.wh.db.router.enums.RoutingConstans;
import cn.wh.db.router.strategy.impl.DefaultDBRouterStrategy;


import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author wh
 * @Description 路由策略配置
 * @Date 2023/3/28 15:39
 * @Version 1.0
 **/

public class DBRoutingContext {

    private static Map<String, IDBRoutingStrategy> dbRoutingStrategyMap = new ConcurrentHashMap<>();


    /**
     * 获取 具体策略实现对象
     *
     * @param dbRoutingConfig
     * @return
     */
    public static IDBRoutingStrategy getDBRoutingStrategy(DBRoutingConfig dbRoutingConfig) {
        IDBRoutingStrategy dbRoutingStrategy = null;
        //如果策略值为空 走默认的策略
        if (StrUtil.isBlankIfStr(dbRoutingConfig.getRoutingStrategy())) {
            dbRoutingStrategy = dbRoutingStrategyMap.get(RoutingConstans.RoutingStrategy.DEFAULT.getDesc());
        } else {
            dbRoutingStrategy = dbRoutingStrategyMap.get(dbRoutingConfig.getRoutingStrategy());
        }
        //判断值是否为空

        //注入 路由配置属性
        if (dbRoutingStrategy.getDBRoutingConfig() == null) {
            dbRoutingStrategy.setDBRoutingConfig(dbRoutingConfig);
        }
        return dbRoutingStrategy;

    }

    /**
     * 走 方法上的注解策略路由
     *
     * @param dbRoutingConfig
     * @param routingStrategy
     * @return
     */
    public static IDBRoutingStrategy getDBRoutingStrategy(DBRoutingConfig dbRoutingConfig, String routingStrategy) {
        IDBRoutingStrategy dbRoutingStrategy = dbRoutingStrategyMap.get(routingStrategy);
        if (dbRoutingStrategy == null) {
            throw new RuntimeException("获取的策略实例对象为空");
        }
        if (dbRoutingStrategy.getDBRoutingConfig() == null) {
            dbRoutingStrategy.setDBRoutingConfig(dbRoutingConfig);
        }
        return dbRoutingStrategy;
    }

    /**
     * 直接根据 策略路由获取 对象
     *
     * @param routingStrategy
     * @return
     */
    public static IDBRoutingStrategy getDBRoutingStrategy( String routingStrategy) {
        IDBRoutingStrategy dbRoutingStrategy = dbRoutingStrategyMap.get(routingStrategy);
        if (dbRoutingStrategy == null) {
            throw new RuntimeException("获取的策略实例对象为空");
        }
        return dbRoutingStrategy;
    }

    /**
     * 添加新的策略
     *
     * @param desc              策略值
     * @param dbRoutingStrategy 策略
     */
    public static void addDBRoutingStrategy(String desc, IDBRoutingStrategy dbRoutingStrategy) {
        if (dbRoutingStrategyMap.containsKey(desc)) {
            throw new RuntimeException("策略值重复,无法重复添加");
        }

        if (dbRoutingStrategy == null) {
            throw new RuntimeException("路由策略对象不能为空");
        }
        dbRoutingStrategyMap.put(desc, dbRoutingStrategy);
    }


}
